<template>
  <div class="manualinput">
    <div class="apptitle"><!-- 发票信息 --></div>
    <div class="content-box">
      <dl>
        <!-- <dt>
          <p>发票信息</p>
          <p>CNY : <span style="color:black;">{{ total }}</span></p>
        </dt> -->
        <dd>
          <div class="input-group flex flex-jus-start">
            <div>发票类型<span class="red">*</span></div>
            <input type="text" v-model="invoiceType" readonly @click="picker=true" placeholder="请选择类型">
            <van-icon name="arrow" size=".3rem" color="#bbb" style="margin-left:0.1rem"/>
          </div>
        </dd>
        <dd v-for="item in list.records" :key="item.index" v-if="item.label" :class="item.type == 0 ? 'nopadding':''">
          
          <div v-if="[2,3,4].includes(item.type)" class="input-group flex flex-jus-start">
            <div>{{ item.label }}<span v-if="item.required" class="red">*</span></div>
            <input type="text" v-model="item.value" readonly @click="timeSelectHand(item)" placeholder="请选择时间">
          </div>
          <div v-if="item.type == 1" class="input-group flex flex-jus-start">
            <div>{{ item.label }}<span v-if="item.required" class="red">*</span></div>
            <input type="text" v-model="item.value" placeholder="请输入内容">
          </div>
          <dl v-if="item.type == 0">
            <dd v-for="w in item.children" :key="w.index">
              <div class="input-group flex flex-jus-start">
                <div>{{ w.label }}</div>
                <input type="text" inputmode="number" v-model="w.value" placeholder="请输入内容">
              </div>
            </dd>
          </dl>

        </dd>
      </dl>
    </div>
    <div class="btn-group flex">
      <div class="btn-submit flex" @click="submit">确认并添加至发票夹</div>
    </div>

    <van-popup v-model="picker" position="bottom">
      <van-picker
        show-toolbar
        title="发票类型"
        :columns="columns"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
    <!-- 年月日时分 -->
    <van-popup v-model="picker1" position="bottom">
      <van-datetime-picker
        v-model="val1"
        type="datetime"
        @cancel="onCancel"
        @confirm="onConfirmTime"
    />
    </van-popup>
    <!-- 年月日 -->
    <van-popup v-model="picker2" position="bottom">
      <van-datetime-picker
        v-model="val2"
        type="date"
        @cancel="onCancel"
        @confirm="onConfirmTime"
    />
    </van-popup>
    <!-- 时分 -->
    <van-popup v-model="picker3" position="bottom">
      <van-datetime-picker
        v-model="val3"
        type="time"
        @cancel="onCancel"
        @confirm="onConfirmTime"
    />
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant-green';
import { addTicket } from '../plugins/api'
import { mapMutations } from 'vuex';
export default {
  name: 'ManualInputView',
  data(){
    return {
      invoiceType : "火车票",
      total       : "",         // 价税合计
      picker      : false,     // 弹窗显示
      picker1     : false,     // 弹窗显示
      picker2     : false,     // 弹窗显示
      picker3     : false,     // 弹窗显示

      val1        : '',
      val2        : '',
      val3        : '',

      currentDate1:"",
      currentDate2:"",
      currentTime :"",
      columns     : [],
      list        : {records:[]},
      index       : 0,
      timeSelectElement:"",
      item:undefined // 存储临时数据
    }
  },
  components: {},
  methods:{
    ...mapMutations(['setFullLoading']),

    timeSelectHand(item){
      this.item = item;
      switch (item.type){
        case 2:
          this.picker1 = true
          console.log(item.type);
          break;
        case 3:
          this.picker2 = true
          console.log(item.type);
          break;
        case 4:
          this.picker3 = true
          console.log(item.type);
          break;
        default:
          break;
      }

    },
    deepCopy(obj) {
      if (typeof obj !== 'object' || obj === null) {
          return obj; // 如果不是对象或者为null，则直接返回
      }
      let copy = Array.isArray(obj) ? [] : {}; // 如果是数组则创建空数组，否则创建空对象
      for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
              copy[key] = this.deepCopy(obj[key]); // 递归调用deepCopy函数
          }
      }
      return copy;
    },
    // 更新发票类型详情
    updateInvoiceList(){
      // 获取所有
      this.billTypeLists = this.deepCopy(this.billTypeListsTemp)
      this.list = this.billTypeLists.filter(v=>v.label == this.invoiceType)[0]
      // this.list.records.map(v=>{
      //   if(v.key == 'totalAmount'){
      //     this.total = v.key
      //   }
      // })
    },
    toLink(url,params = {}){
      console.log(params);
      this.$router.push({ path: url, query: params });
    },
    onConfirm(value, index){
      console.log(value, index);
      this.index       = index
      this.invoiceType = value;
      if(!isNaN(index)){ // 如果是数字则为true
        this.updateInvoiceList() // 更新填写的信息
      }
      this.picker  = false
      this.picker1 = false
      this.picker2 = false
      this.picker3 = false
    },
    onConfirmTime(value){
      this.picker  = false
      this.picker1 = false
      this.picker2 = false
      this.picker3 = false
      if(this.item == 4){
        this.item.value = value
      }else{
        const date   = new Date(value);
        const year   = date.getFullYear();
        const month  = (date.getMonth() + 1).toString().padStart(2, '0');
        const day    = date.getDate().toString().padStart(2, '0');
        const hours  = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes().toString().padStart(2, '0');
        switch(this.item.type){
          case 2:
            this.item.value = `${year}-${month}-${day} ${hours}:${minute}`
            break;
          case 3:
            this.item.value = `${year}-${month}-${day}`
            break;
          default:
          this.item.value = ''
            break;
        }
      }
      console.log(this.item.value);
    },
    onCancel(){
      this.picker  = false // 直接关闭
      this.picker1 = false // 直接关闭
      this.picker2 = false // 直接关闭
      this.picker3 = false // 直接关闭
    },
    submit(){
      // 判断是否有为空值
      let verify = this.list.records.every(v=>{
        // 如果不是必填则直接返回true
        if(!v.required){ 
          return true
        }
        // 如果有子项则直接返回true
        if(v.children){
          return true
        }
        return v.value
      })
      if(!verify){
        Toast('有必填项没有填写')
      }else{
        this.$store.commit('setFullLoading',true)
        console.log(this.list);
        // demo
        let obj = {
            "op"      : "invoice",
            "ftype"   : this.index,
            "index"   : 1,
            "type"    : this.invoiceType,
            "userId"  : localStorage.getItem('userId'),
            "data"    : {},
        }
        // let obj2 = {}
        // console.log("this.list:",this.list);
        // this.list.records.map(v=>{
        //   obj2[v.key] = v.value
        // })
        
        let obj2 = {}
        this.list.records.map(v=>{
        if(v.children){
          let arr = [{}]
          //二级数组
          v.children.map(w=>{
            arr[0][w.key] = w.value
          })
          obj2[v.key] = arr
        }else{
          obj2[v.key] = v.value
        }

        obj2['id'] = 0
        obj.data = obj2

      })







        // 保存数据到vuex
        addTicket({...obj}).then(res=>{
          this.$store.commit('setFullLoading',false)
          if(res.code == 200){
            Toast(res.msg)
            setTimeout(()=>{
              // 提交成功以后跳转到发票列表页
              this.$router.push({path:'/invoicelist'})
            },1500)
          }else{
            Toast(res.msg)
          }
          // console.log(res);
        }).catch(error=>{
          console.log(error);
          this.$store.commit('setFullLoading',false)
          Toast(error.errMsg)
        })
      }
    }
  },
  mounted(){

    this.val1 = new Date()
    this.val2 = new Date()
    this.val3 = new Date()

    this.$store.commit('setFullLoading',false)
    // 默认获取发票类型列表
    this.billTypeLists = [...this.$store.state.billTypeLists]

    this.billTypeListsTemp = this.deepCopy(this.billTypeLists);
    // 保存列表类型
    this.list = [...this.$store.state.billTypeLists]
    // this.list.records.map(v=>{
    //   if(v.key == 'totalAmount'){
    //     this.total = v.key
    //   }
    // })
    let arr = []
    this.billTypeLists.map(v=>{
      arr.push(v.label)
    })
    this.columns = arr
    // console.log(this.columns);
    // console.log(this.billTypeLists);
    this.updateInvoiceList()
  },

  //设置title的钩子
  beforeRouteEnter(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
  beforeRouteUpdate(to, from, next) {
    document.title = to.meta.title || 'Default Title';
    next();
  },
}
</script>
<style>
.van-picker__confirm {
  color:#4273D9!important;
}
</style>
<style scoped>

.content-box {
  background-color: white;
  box-shadow: 0 0.05rem 0.15rem rgba(0, 0, 0, 0.1);
  border-radius: 0.1rem;
  margin:0.25rem;
}
dl {
  font-size: 0.3rem;
}
dl dt,
dl dd {
  color:#777;
  border-bottom: 0.01rem solid #eee;
  padding:0.15rem 0.25rem;
  line-height: 1.7;
}
dl dd {
  line-height: 1;
  padding:0.3rem 0.25rem;
}
.input-group > div {
  width: 2.2rem;
}
.van-popup {
  width: 100%!important;
}
.input-group input {
  text-align: left;
  outline: none;
  border:none;
  -webkit-appearance: none;
  appearance: none;
  font-size: .3rem;
  line-height: 1;
  flex: 1;
}
.input-group input::-webkit-input-placeholder {
  color:#ccc;
}
.red {
  color:#FF5F4E;
}
.picker {
  position: fixed;
  width:7.5rem;
  height:4.5rem;
  background-color: white;
  left:50%;
  bottom:0;
  transform: translateX(-50%);
  z-index: 99999;
}

.btn-group {
  width:7.5rem;
  position: fixed;
  left:50%;
  bottom:0;
  z-index: 99;
  transform: translateX(-50%);
  padding:.2rem 0.5rem;
  background-color: white;
  box-shadow: 0 0 0.15rem rgba(0, 0, 0, 0.15);
}
.btn-submit {
  width:5rem;
  height:.8rem;
  border-radius: 100rem;
  border:none;
  outline: none;
  appearance: none;
  line-height: 1;
  background-color: #4273D9;
  color:white;
  font-size: .3rem;
  margin:0 auto;
}
.btn-edit {
  width:1.5rem;
  height:.8rem;
  border-radius: 100rem;
  border:1px solid #4273D9;
  color:#4273D9;
  outline: none;
  appearance: none;
  line-height: 1;
  background-color: white;
  font-size: .3rem;
  margin-right: .25rem;
}
.nopadding {
  padding: 0!important;
}
</style>